package 二叉树.根节点到叶节点之和;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/2/28 17:02
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1,new TreeNode(2),new TreeNode(3));
        sumNumbers(root);
    }

    public static int sumNumbers(TreeNode root) {
        List<String> paths = new ArrayList<>();
        countLeafSum(root,"",paths);
        int ans = 0;
        for (String numStr : paths) {
            ans += Integer.valueOf(numStr);
        }
        return ans;
    }

    private static void countLeafSum(TreeNode root, String path, List<String> paths) {
        if (root != null){
            StringBuilder sb = new StringBuilder(path);
            sb.append(root.val);
            if (root.left == null && root.right == null){
                paths.add(sb.toString());
            }else {
                countLeafSum(root.left,sb.toString(),paths);
                countLeafSum(root.right,sb.toString(),paths);
            }
        }
    }

}
